package jeopardy.common;

import java.io.InputStream;

public class Utils {
	
	/**
	 * Given the inputstream and the output buffer, read a jeopardy message into the buffer <code>out</code>
	 * 
	 * @param in
	 * @param out
	 * @return <code>out</code> modified to contain the message.  returns int which indicates the length of message in <code>out</code>.  -1 if error.
	 * @throws Exception
	 */
	public static int readBytes(InputStream in, byte[] out) throws Exception{
		int numRead = 0;
		int curRead = 0;
		int lastRead = 0;
		
		while(curRead != -1 && numRead < out.length && lastRead != Consts.MSG_DELIM){
			curRead = in.read(out, numRead, out.length - numRead);
			numRead = numRead + curRead;
			if(numRead > 0){
				lastRead = out[numRead -1];
			}
		}
		if(out[numRead -1] != Consts.MSG_DELIM){
			return -1;
		}else{
			return numRead - 1; //strip the delimeter
		}
	}
}
